import 'package:flutter/material.dart';
import 'pwd_card.dart';
import 'pwd_info.dart';
import 'database_helper.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

List<Item> dataList = new List(); //所有密码
var db = DatabaseHelper();

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  String _eventInfo = '';

  void initState() {
    super.initState();
    _getDataFromDb(); //读取数据库数据

    eventBus.on<CustomEvent>().listen((event) {
      setState(() {
        _eventInfo = event.info;
        List<String> cmd = _eventInfo.split('_');
        if (cmd.length != 2) return;
        if (cmd.contains('get')) {
          //查询
          print('command get ' + cmd[1]);
          _getItem(int.parse(cmd[1]));
        } else if (cmd.contains('insert')) {
          //新建
          Navigator.push(context, MaterialPageRoute(builder: (context) {
            return PwdInfoPage(
              type: 1,
            );
          }));
        } else if (cmd.contains('update')) {
          //刷新
          _getDataFromDb();
        }
      });
    });
  }

  void dispose() {
    eventBus.destroy();
    db.close();
    super.dispose();
  }

  //查询
  void _getItem(int id) async {
    Item curItem = await db.getItem(id);
    print('getItem....' +
        curItem.note +
        curItem.phoneNum +
        curItem.accountPwd +
        " " +
        curItem.accountName);

    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return PwdInfoPage(
        data: curItem,
        type: 0,
      );
    }));
  }

  void _getDataFromDb() async {
    dataList.clear();
    List datas = await db.getTotalList();
    print('查询到数据...' + datas.length.toString());
    if (datas.length > 0) {
      datas.forEach((element) {
        Item item = Item.fromMap(element);
        dataList.add(item);
      });
    }

    setState(() {});
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('密码'),
      ),
      body: PwdList(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          eventBus.fire(CustomEvent("insert_" + '0'));
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

//搜索框
class TextFieldWidget extends StatelessWidget {
  Widget buildTextField() {
    // theme设置局部主题
    return Theme(
      data: new ThemeData(primaryColor: Colors.grey),
      child: new TextField(
        cursorColor: Colors.grey, // 光标颜色
        // 默认设置
        decoration: InputDecoration(
            contentPadding: const EdgeInsets.symmetric(vertical: 10.0),
            border: InputBorder.none,
            icon: Icon(Icons.search),
            hintText: "搜索...",
            hintStyle: new TextStyle(
                fontSize: 14, color: Color.fromARGB(50, 0, 0, 0))),
        style: new TextStyle(fontSize: 14, color: Colors.black),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      // 修饰搜索框, 白色背景与圆角
      decoration: new BoxDecoration(
        color: Colors.white,
        borderRadius: new BorderRadius.all(new Radius.circular(10.0)),
      ),
      alignment: Alignment.center,
      height: 36,
      padding: EdgeInsets.fromLTRB(10.0, 0.0, 10.0, 0.0),
      child: buildTextField(),
    );
  }
}

class PwdList extends StatelessWidget {
  const PwdList({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      itemCount: dataList.length,
      itemBuilder: (context, index) {
        return PwdCard(data: dataList[index]);
      },
      separatorBuilder: (context, index) {
        return Divider(
          height: .5,
          indent: 75,
          color: Color(0xFFDDDDDD),
        );
      },
    );
  }
}
